import { ResponseInterceptor } from './../../../interceptor/response/response.interceptor';
import { NavService } from './../../../service/nav/nav.service';
import config from 'src/config/config';
import { Body, Controller, Delete, Get, Patch, Post, Query, UseInterceptors } from '@nestjs/common';
import * as mongoose from 'mongoose';

@Controller(`${config.adminPath}/nav`)
@UseInterceptors(ResponseInterceptor)
export class NavController {
    constructor(private readonly navService: NavService) {}
    @Get()
    async find(@Query() query) {
        const aggregateOptions: any[] = [
            { $sort: { position: 1, sort: -1 } },
            {
                $lookup: {
                    localField: 'relation',
                    foreignField: '_id',
                    from: 'goods',
                    as: 'relation',
                },
            },
        ];
        const { page, pageSize } = query;
        if (page && pageSize) {
            aggregateOptions.push({ $skip: (+page - 1) * +pageSize });
            aggregateOptions.push({ $limit: +pageSize });
            const total = await this.navService.getModel().count();
            const data = await this.navService.getModel().aggregate(aggregateOptions);
            return { data, total };
        } else {
            return await this.navService.getModel().aggregate(aggregateOptions);
        }
    }
    @Post()
    async create(@Body() body) {
        const { relation } = body;
        if (relation && relation.length) {
            body.relation = relation.map((item) => new mongoose.Types.ObjectId(item));
        }
        return await this.navService.create(body);
    }
    @Patch()
    async update(@Body() body) {
        const { relation } = body;
        if (relation && relation.length) {
            body.relation = relation.map((item) => new mongoose.Types.ObjectId(item));
        }
        return await this.navService.update(body);
    }
    @Delete()
    async delete(@Body() body) {
        return await this.navService.delete(body);
    }
}
